package org.light.shiroauth.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.complexverb.Assign;
import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.FieldSerialComparator;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.oracle.generator.MybatisOracleSqlReflector;
import org.light.utils.FieldUtil;
import org.light.utils.InterVarUtil;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;
import org.light.verb.FindByName;

public class RegisterUser extends Verb implements EasyUIPositions {
	protected Domain roleDomain;

	public Domain getRoleDomain() {
		return roleDomain;
	}

	public void setRoleDomain(Domain roleDomain) {
		this.roleDomain = roleDomain;
	}

	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+StringUtil.capFirst(this.domain.getStandardName()));		
			method.setNoContainer(true);
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(100L,1,"<insert id=\""+StringUtil.lowerFirst(this.getVerbName())+"\" parameterType=\""+this.domain.getFullName()+"\">"));
			if ("Oracle".equalsIgnoreCase(this.dbType)) {
				list.add(new Statement(200L,2, MybatisOracleSqlReflector.generateInsertSql(domain)));
			}else {
				list.add(new Statement(200L,2, MybatisSqlReflector.generateInsertSql(domain)));
			}
			list.add(new Statement(300L,1,"</insert>"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("Boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("Boolean"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport("org.springframework.transaction.annotation.Transactional");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getDaoSuffix()+"."+this.domain.getStandardName()+"Dao");
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addMetaData("Override");		
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
					
			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,2, InterVarUtil.DB.dao.getVarName()+ ".register"+domain.getStandardName()+"("+domain.getLowerFirstDomainName()+");"));
			list.add(new Statement(2000L,2,"return true;"));
			method.setMethodStatementList(WriteableUtil.merge(list));
			return method;
		}
	}

	public RegisterUser(Domain domain, Domain roleDomain) throws ValidateException{
		super();
		this.domain = domain;
		this.roleDomain = roleDomain;
		this.dbType = domain.getDbType();
		this.denied = domain.isVerbDenied("RegisterUser");
		this.setVerbName("Register"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("注册");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("RegisterUser");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+this.domain.getCapFirstDomainName());
			method.setReturnType(new Type("Map<String,Object>"));
			method.setThrowException(true);
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addAdditionalImport(this.domain.getPackageToken()+"."+this.domain.getServiceSuffix()+"."+this.domain.getStandardName()+"Service");
			method.addSignature(new Signature(1,this.domain.getLowerFirstDomainName(),this.domain.getType(),this.domain.getPackageToken(),"RequestBody"));
			method.addMetaData("RequestMapping(value = \"/register"+this.domain.getCapFirstDomainName()+"\", method = RequestMethod.POST)");

			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,2,"Map<String,Object> result = new TreeMap<String,Object>();"));
			sList.add(new Statement(2000L,2,"String "+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+" = "+this.domain.getLowerFirstDomainName()+".get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"();"));
			sList.add(new Statement(3000L,2,"String "+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+" = "+this.domain.getLowerFirstDomainName()+".get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"();"));
			
			CountByName count = new CountByName(this.domain);
			
			sList.add(new Statement(4000L,2,"int "+this.domain.getLowerFirstDomainName()+"Count = service."+StringUtil.lowerFirst(count.getVerbName())+"("+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+");"));
			sList.add(new Statement(4100L,2,"if ("+this.domain.getLowerFirstDomainName()+"Count==0) {"));
			sList.add(new Statement(5000L,3,"String[] saltAndCiphertext = UserRegisteAndLogin.encryptPassword("+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+");"));
			sList.add(new Statement(6000L,0,""));
			sList.add(new Statement(7000L,3,""+this.domain.getLowerFirstDomainName()+".set"+this.domain.findFieldByFixedName("salt").getCapFirstFieldName()+"(saltAndCiphertext[0]);"));
			sList.add(new Statement(8000L,3,""+this.domain.getLowerFirstDomainName()+".set"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"(saltAndCiphertext[1]);"));
			sList.add(new Statement(8100L,3,""+this.domain.getLowerFirstDomainName()+".set"+this.domain.findFieldByFixedName("loginFailure").getCapFirstFieldName()+"(0);"));
			sList.add(new Statement(9000L,0,""));
			long serial = 10000L;
			boolean imageExists = false;
			for (Field f:this.domain.getPlainFields()) {
				if (f.getFieldType().equalsIgnoreCase("image")) {
					imageExists = true;
					sList.add(new Statement(serial,3,"if (temp"+this.domain.getCapFirstDomainName()+"!=null && temp"+this.domain.getCapFirstDomainName()+".get"+f.getCapFirstFieldName()+"()!=null) {"));
					sList.add(new Statement(serial+1000L,4,this.domain.getLowerFirstDomainName()+".set"+f.getCapFirstFieldName()+"(temp"+this.domain.getCapFirstDomainName()+".get"+f.getCapFirstFieldName()+"());"));
					sList.add(new Statement(serial+2000L,3,"}"));
					serial += 3000L;
				}				
			}
			if (imageExists) 
			{
				sList.add(new Statement(serial+1000L,3,"temp"+this.domain.getCapFirstDomainName()+" = new  "+this.domain.getCapFirstDomainNameWithSuffix()+"();"));
				serial += 2000L;
			}
			
			sList.add(new Statement(serial+10000L,3,"service.register"+this.domain.getCapFirstDomainName()+"("+this.domain.getLowerFirstDomainName()+");"));
			
			FindByName findUser = new FindByName(this.domain);
			FindByName findRole = new FindByName(this.roleDomain);
			Assign assignRole = new Assign(this.domain,this.roleDomain);
			
			sList.add(new Statement(serial+10100L,3,""+this.domain.getLowerFirstDomainName()+" = service."+StringUtil.lowerFirst(findUser.getVerbName())+"("+this.domain.getLowerFirstDomainName()+".get"+this.domain.getDomainName().getCapFirstFieldName()+"());"));
			sList.add(new Statement(serial+10200L,3,this.roleDomain.getCapFirstDomainNameWithSuffix()+" "+this.roleDomain.getLowerFirstDomainName()+" = "+this.roleDomain.getLowerFirstDomainName()+"Service."+StringUtil.lowerFirst(findRole.getVerbName())+"(\"user\");"));
			sList.add(new Statement(serial+10300L,3,"service."+StringUtil.lowerFirst(assignRole.getVerbName())+"("+this.domain.getLowerFirstDomainName()+".get"+this.domain.getDomainId().getCapFirstFieldName()+"(), \"\"+"+this.roleDomain.getLowerFirstDomainName()+".get"+this.roleDomain.getDomainId().getCapFirstFieldName()+"());"));
			
			sList.add(new Statement(serial+11000L,0,""));
			sList.add(new Statement(serial+12000L,3,"result.put(\"success\",true);"));
			sList.add(new Statement(serial+13000L,3,"result.put(\"data\",null);"));
			sList.add(new Statement(serial+14000L,3,"return result;"));
			
			sList.add(new Statement(serial+15000L,2,"}else {"));
			sList.add(new Statement(serial+16000L,3,"result.put(\"success\",false);"));
			sList.add(new Statement(serial+17000L,3,"result.put(\"data\",null);"));
			sList.add(new Statement(serial+18000L,3,"return result;"));
			sList.add(new Statement(serial+19000L,2,"}"));

			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}	

	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("register"+domain.getCapFirstDomainName());
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,0, "{"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(2000, 1, "text:'Add',"));
			}else {
				sl.add(new Statement(2000,1, "text:'新增',"));
			}
			sl.add(new Statement(3000,1, "iconCls:'icon-add',"));
			sl.add(new Statement(4000,1, "handler:function(){"));
			sl.add(new Statement(5000,2, "$('#wadd"+this.domain.getCapFirstDomainName()+"').window('open');"));
			sl.add(new Statement(6000,1, "}"));
			sl.add(new Statement(7000,0, "}"));
			block.setMethodStatementList(sl);
			return block;			
		}
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("register"+domain.getCapFirstDomainName());
			
			StatementList sl = new StatementList();
			sl.add(new Statement(100L,2,"if (isBlank($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").val())||isBlank($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val())||isBlank($(\"#ff\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val())){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sl.add(new Statement(200L,3,"$.messager.alert(\"Error\",\"Necessary field is blank.\",\"error\");"));
			}else {
				sl.add(new Statement(200L,3,"$.messager.alert(\"错误\",\"必须字段为空！\",\"error\");"));
			}
			sl.add(new Statement(300L,3,"return;"));
			sl.add(new Statement(400L,2,"}"));
			
			sl.add(new Statement(1000L,0,"if ($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val()!=$(\"#ff\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val()){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sl.add(new Statement(2000L,3,"$.messager.alert(\"Error\",\"Password did not match.\",\"error\");"));
			}else {
				sl.add(new Statement(2000L,3,"$.messager.alert(\"错误\",\"密码不匹配！\",\"error\");"));
			}
			sl.add(new Statement(3000L,3,"return;"));
			sl.add(new Statement(4000L,2,"}"));

			sl.add(new Statement(5000,2, "$.ajax({"));
			sl.add(new Statement(6000,3, "type: \"post\","));
			sl.add(new Statement(7000,3, "url: \"../"+this.domain.getControllerPackagePrefix()+"login"+domain.getControllerNamingSuffix()+"/register"+domain.getCapFirstDomainName()+"\","));
			sl.add(new Statement(8000,3, "data: JSON.stringify({"));
			sl.add(new Statement(9000,4, this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").textbox(\"getValue\"),"));
			sl.add(new Statement(10000,4, this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+":hex_sha1($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").textbox(\"getValue\")),"));
			long serial = 11000;
			Set<Field> normalFields = new TreeSet<>(new FieldSerialComparator());
			normalFields.addAll(domain.getFieldsWithoutIdAndActive());
			Set<Field> deniedFields = new TreeSet<>(new FieldSerialComparator());
			deniedFields.add(this.domain.findFieldByFixedName("password"));
			deniedFields.add(this.domain.findFieldByFixedName("salt"));
			deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
			normalFields = FieldUtil.filterDeniedFields(normalFields,deniedFields);
			for (Field f: normalFields){
				if (f instanceof Dropdown){
					sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+f.getLowerFirstFieldName()+"\").combobox(\"getValue\"),"));
				} else if (f.getFieldType().equalsIgnoreCase("boolean")||f.getOriginalType().equalsIgnoreCase("boolean")){
					if ("Oracle".equalsIgnoreCase(this.domain.getDbType())){
						sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":parseBooleanInt($(\"#ff\").find(\"input[name='"+f.getLowerFirstFieldName()+"']:checked\").val()),"));								
					}else {
						sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":parseBoolean($(\"#ff\").find(\"input[name='"+f.getLowerFirstFieldName()+"']:checked\").val()),"));								
					}
				} else {
					sl.add(new Statement(serial,4, f.getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+f.getLowerFirstFieldName()+"\").val(),"));
				}
				serial+=1000;
			}
			if (this.domain.hasActiveField()) {
				if ("Oracle".equalsIgnoreCase(this.domain.getDbType())) {
					sl.add(new Statement(serial,4, this.domain.getActive().getLowerFirstFieldName()+":parseBooleanInt($(\"#ff\").find(\"input[name='"+this.domain.getActive().getLowerFirstFieldName()+"']:checked\").val()),"));
				}else {
					sl.add(new Statement(serial,4, this.domain.getActive().getLowerFirstFieldName()+":parseBoolean($(\"#ff\").find(\"input[name='"+this.domain.getActive().getLowerFirstFieldName()+"']:checked\").val()),"));
				}
			}
			sl.add(new Statement(serial,3, "}),"));
			sl.add(new Statement(serial+1000,3, "dataType: 'json',"));
			sl.add(new Statement(serial+2000,3, "contentType:\"application/json;charset=UTF-8\","));
			sl.add(new Statement(serial+3000,3, "success: function(data, textStatus) {"));
			sl.add(new Statement(serial+4000,4, "if (data.success) {"));
			sl.add(new Statement(serial+5000,5, "$('#ff').form('clear');"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sl.add(new Statement(serial+6000,5, "$.messager.alert(\"Info\",\"Register new user successfully.\",\"info\");"));
			} else {
				sl.add(new Statement(serial+6000,5, "$.messager.alert(\"信息\",\"注册新用户成功！\",\"info\");"));
			}
			sl.add(new Statement(serial+7000L,4,"} else if (data.success == false){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sl.add(new Statement(serial+8000L,5,"$.messager.alert(\"Error\",\"Register user failed.\",\"error\");"));
			}else {
				sl.add(new Statement(serial+8000L,5,"$.messager.alert(\"错误\",\"注册用户失败！\",\"error\");"));
			}
			sl.add(new Statement(serial+9000L,4,"}"));
			sl.add(new Statement(serial+10000,4, "},"));
			sl.add(new Statement(serial+11000,3, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(serial+12000,3, "},"));
			sl.add(new Statement(serial+13000,3, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(serial+14000,4, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(serial+15000,4, "alert(errorThrown.toString());"));
			sl.add(new Statement(serial+16000,3, "}"));
			sl.add(new Statement(serial+17000,2, "});"));
			
			method.setMethodStatementList(sl);
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("register"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			
			List<Writeable> sList = new ArrayList<Writeable>();			
			sList.add(new Statement(1000L,2, this.domain.getLowerFirstDomainName()+".set"+this.domain.getDomainId().getCapFirstFieldName()+"(maxId()+1);"));
			sList.add(new Statement(2000L,2,"db.add("+this.domain.getLowerFirstDomainName()+");"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

}
